//
//  TalkfunExaminationView.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2021/11/24.
//  Copyright © 2021 Talkfun. All rights reserved.
//

import UIKit

class TalkfunExaminationView: UIView ,UICollectionViewDelegate, UICollectionViewDataSource
{
    @objc public weak var delegate : TalkfunExaminationViewDelegate?
    //倒计时定时器
    var timer:Timer!
    var isAddFillet: Bool = false
    @objc public let collectionView = UICollectionView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: UICollectionViewFlowLayout())

    let TalkFunCollectionViewCell = "TalkFunCollectionViewCell"
    //标题
    var title:UILabel = UILabel()
    //列表的父模型
    var examinationResult:TalkfunQuestionnaireResult?
    //关闭
    @objc public let close:TalkfunIncreaseButton = TalkfunIncreaseButton()
    
    var ID = -1000 as NSInteger
    @objc public var YEqualsHigh = false
    @objc public var dataList:NSMutableArray = NSMutableArray.init()
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.collectionView.backgroundColor = UIColor.clear
        self.addSubview(self.collectionView)
        self.collectionView.dataSource = self
        self.collectionView.delegate = self
        self.collectionView.register(TalkfunExamDirectoryCollectionViewCell.self, forCellWithReuseIdentifier:TalkFunCollectionViewCell)
        
        self.backgroundColor = UIColor.init(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
        
        self.title.textAlignment = NSTextAlignment.center
        self.title.text = "问卷"
        self.title.font = UIFont(name: "PingFang SC", size: 18)
        self.title.textColor = UIColor(red: 0.08, green: 0.09, blue: 0.1,alpha:1)
        self.addSubview(self.title)
     
        //关闭
        self.close.layer.cornerRadius = 2;
        self.addSubview(self.close)
        self.close.setImage(UIImage.init(named: "HTLive.bundle/examinatioCclose_slices"), for: UIControl.State.normal)
        self.close.backgroundColor = UIColor.clear

    }

    override func layoutSubviews() {
        super.layoutSubviews()
        
        if (self.isAddFillet == false || self.collectionView.frame.width != self.frame.width)
        {
            let maskPath = UIBezierPath.init(roundedRect: self.bounds, byRoundingCorners:[UIRectCorner.topRight,UIRectCorner.topLeft], cornerRadii: CGSize(width: 10, height: 10))
            
            let  maskLayer = CAShapeLayer()
            maskLayer.frame = self.bounds
            maskLayer.path = maskPath.cgPath
            
            self.layer.mask = maskLayer
            self.isAddFillet = true
        }

        
        //TODO:标题
        self.title.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: 62.0)
        
        if (self.collectionView.frame.width != self.frame.width)
        {
            let collectionViewW = self.frame.size.width
            let collectionViewH = self.frame.size.height - 62.0
            let collectionViewFrame = CGRect(x: 0, y: self.title.frame.height, width: collectionViewW , height: collectionViewH)
            
            let collectionViewCellW = self.frame.size.width - 12.0 - 12.0
            let collectionViewCellH = 90.0
            
            let layout = UICollectionViewFlowLayout();
            layout.itemSize =  CGSize(width: collectionViewCellW, height: collectionViewCellH);
            layout.minimumLineSpacing = 8

            self.collectionView.frame = collectionViewFrame
            self.collectionView.reloadData()
            //刷新一下cell
            self.collectionView.collectionViewLayout.invalidateLayout()
            self.collectionView.layoutIfNeeded()
            self.collectionView.collectionViewLayout = layout
        }
      
       
        let closeY = 15.0
        let closeW = 15.0
        let closeX = self.frame.width - 15.0 - 15.0
        let closeH = 15.0
        
        self.close.frame = CGRect(x: closeX, y: closeY, width: closeW, height: closeH)
        
    }
    
    @objc public func reload(isShow:Bool)
    
    {
        if (isShow && (self.superview != nil))
        {
            self.YEqualsHigh = false
            if ((self.superview) != nil) {
                self.superview?.bringSubviewToFront(self)
            }
            UIView.animate(withDuration: 0.5) {
                self.frame = CGRect(x: self.frame.origin.x, y: 0.0, width: self.frame.size.width, height: self.frame.size.height)
                
            }
           
        }
    }
    @objc public func addData(_ result:TalkfunQuestionnaireResult)
    {
        
        self.examinationResult = result
        self.dataList = NSMutableArray.init(array: result.data)
        self.collectionView.reloadData()
        
        //倒计时
        self.initTimer()
    }
    
    @objc func timerInvalidate()
    
    {
        if((self.timer) != nil)
        {
            self.timer.invalidate()
            self.timer = nil
        }
    }
    
    @objc func initTimer()
    {
        if((self.timer) == nil)
        {
            self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(startCountdown), userInfo: nil, repeats: true)
            RunLoop.main.add(self.timer! , forMode: RunLoop.Mode.default)
            self.timer.fire()
        }
    }
    @objc public func addExamination(_ model:TalkfunQuestionnaire  )
    {
        self.dataList.insert(model, at: 0)
        self.collectionView.reloadData()
        
        self.initTimer()
    }
    //更新状态
    @objc public func reloadAnswerStatus(_ newModel:TalkfunSubjectExamineAnswerInfo  )
    
    {
        for i in stride(from: 0, to: self.dataList.count ,by: 1) {
            let model = self.dataList[i] as! TalkfunQuestionnaire
            if(model.id == newModel.id)
            {
                model.answerStatus = newModel.answerStatus
            
            }
            
        }
        
    }
    
    
    //TODO: 数组源
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.dataList.count
    }
    //TODO: cell的创建
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TalkFunCollectionViewCell, for: indexPath) as! TalkfunExamDirectoryCollectionViewCell
        cell.tag = indexPath.row
        let model = self.dataList[indexPath.row] as! TalkfunQuestionnaire

        
        let attributes = [NSMutableAttributedString.Key.backgroundColor:UIColor.clear,          NSMutableAttributedString.Key.font:UIFont(name: "PingFang SC", size: 16) as Any,NSMutableAttributedString.Key.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2,alpha:1)]
        cell.title.attributedText = NSAttributedString.init(string:model.title, attributes: attributes)

        //0 已经有答题,但未提交
        if (model.answerStatus == TalkfunAnswerStatusParticipated )
        {
             //空白  左下的
            cell.answerStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.promptAnswerStatus.blank, amount: "")
            /**2:随堂考 3.问卷 4.快速答题卡*/
            if model.type == TFExaminationTypeTestPaper {
                //立即作答  右边的
                cell.paperStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.paperStatus.answer_now)
                cell.answerTime.isHidden = false
            }else if model.type == TFExaminationTypeTable {
                cell.paperStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.paperStatus.fillIn)
                cell.answerTime.isHidden = true
            }
            
            
        }else if (model.answerStatus == TalkfunAnswerStatusSubmitted )
        {
            
            // 1已提交
            
            //表单
            if (model.type == TFExaminationTypeTable) {
                cell.answerStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.promptAnswerStatus.submitted, amount: NSString(format: "%i", model.score))
            }else{
                //答对XX题
                cell.answerStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.promptAnswerStatus.correctAnswer, amount: NSString(format: "%i", model.score))
            }
            
           
            //查看
            cell.paperStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.paperStatus.check)
            cell.answerTime.isHidden = true
            
            
        }else if (model.answerStatus == TalkfunAnswerStatusApproved )
        {  //2已批阅 或者已提交  根据问卷类型决定:随堂考,表单
            
            //表单
            if (model.type == TFExaminationTypeTable) {
                cell.answerStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.promptAnswerStatus.submitted, amount: NSString(format: "%i", model.score))
            }else
            {
                cell.answerStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.promptAnswerStatus.correctAnswer, amount: NSString(format: "%i", model.score))
            }
            
            
            cell.paperStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.paperStatus.check)
            cell.answerTime.isHidden = true
        }else if (model.answerStatus == TalkfunAnswerStatusUnsubmitted )
        {   //未参加
            //结束了
            if(model.isEndOfTestPaper)
            {
                //未作答
                cell.answerStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.promptAnswerStatus.unanswered, amount: "")
                //查看
                cell.paperStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.paperStatus.check)
            }else
            {   //未结束
                //空白
                //未作答  左下的
                cell.answerStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.promptAnswerStatus.blank, amount: "")
               
                /**2:随堂考 3.问卷 4.快速答题卡*/   //立即作答  右边的
                if model.type == TFExaminationTypeTestPaper {
                    //立即作答  右边的
                    cell.paperStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.paperStatus.answer_now)
                    cell.answerTime.isHidden = false
                }else if model.type == TFExaminationTypeTable {
                    cell.paperStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.paperStatus.fillIn)
                    cell.answerTime.isHidden = true
                }
                
            }
          
        }
   
        let subjectTotalStr = NSString(format: "共%i题", model.subjectTotal)
        
        let numberOfQuestionsAttributes = [NSMutableAttributedString.Key.backgroundColor:UIColor.clear,          NSMutableAttributedString.Key.font:UIFont(name: "PingFang SC", size: 14) as Any,NSMutableAttributedString.Key.foregroundColor: UIColor(red: 0.59, green: 0.63, blue: 0.67,alpha:1)]
        cell.numberOfQuestions.attributedText = NSAttributedString.init(string:subjectTotalStr as String, attributes: numberOfQuestionsAttributes)
        cell.operate.tag = indexPath.row
        cell.operate.addTarget(self, action: #selector(self.operateClick), for: UIControl.Event.touchUpInside)
        
        return cell
    }

    
    //TODO:點選 cell 後執行的動作
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
 
        
    }
    

    @objc func closeClick(){
        
//        print("触发关闭窗口")
        UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.allowAnimatedContent) {
            self.YEqualsHigh = true
            self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y + self.frame.size.height, width: self.frame.size.width, height: self.frame.size.height)
        } completion: { Bool in
            
        }

        
    }
    //考试ID
    @objc public func examinationDelete(_ ID:NSInteger)
    {
        
        for i in stride(from: 0, to: self.dataList.count ,by: 1) {
            let model = self.dataList[i] as! TalkfunQuestionnaire
            if(model.id == ID)
            {
                self.dataList.remove(model)
                self.collectionView.reloadData()
                return
            }
        }
    }


    @objc func startCountdown()
    {
        if Thread.isMainThread {
            //code
            let visibleCells =  self.collectionView.visibleCells
         
           
            for i in stride(from: 0, to: visibleCells.count ,by: 1) {
                
                let cell = visibleCells[i] as! TalkfunExamDirectoryCollectionViewCell
                
                if (cell.tag < self.dataList.count )
                {
                    let model = self.dataList[cell.tag] as! TalkfunQuestionnaire

                    if (model.endTime >= TalkfunSharedTools.getCurrentDateString() && model.isEndOfTestPaper == false )
                        
                    {
                      //考试未结束
                        let countdownStr = TalkfunSharedTools.timeDifference(endTime: model.endTime)
                        cell.answerTime.text = countdownStr as String
                        
      
                    }else{
                        cell.paperStatusSwitch(status: TalkfunExamDirectoryCollectionViewCell.paperStatus.check)
                        
                        cell.answerTime.text = ""
                        if(model.isPopup == false)
                        {
                            model.isPopup = true
                            
                            if (self.ID == model.id)
                            {
                                //答题时间到
                                if (model.answerStatus == TalkfunAnswerStatusUnsubmitted) {
                                   ////未参加    答题时间到(试题已自动提交)
                                    TalkfunAlertNewView.shareInstance(type: TalkfunAlertNewView.TalkfunAlertType.endOfExamTime, target: self, action: #selector(self.seeDetails),ID:model.id)
                                    return
                                }else
                                {

                                    //已参加 答题时间到
                                    TalkfunAlertNewView.shareInstance(type: TalkfunAlertNewView.TalkfunAlertType.endOfExamTimeAndTheStudentHasSubmitted, target: self, action: #selector(self.seeDetails),ID:model.id)
                                    return
                                }
                            }else{
                                
                                //
                                if (model.answerStatus == TalkfunAnswerStatusUnsubmitted) {
                                   ////未参加  另一个测试答题时间到
                                    TalkfunAlertNewView.shareInstance(type: TalkfunAlertNewView.TalkfunAlertType.otherTestQuestionsEndedAndTheStudentHasSubmitted, target: self, action: #selector(self.seeDetails),ID:model.id)
                                    return
                                }else
                                {
                                    //已参加   另一个测试答题时间到 (试题已自动提交)
                                    TalkfunAlertNewView.shareInstance(type: TalkfunAlertNewView.TalkfunAlertType.otherTestQuestionsEnded, target: self, action: #selector(self.seeDetails),ID:model.id)
                                    return

                                }
                            }
                           
                        }
                       
                        
                    }
                   
                }
               

            }
        } else {
            DispatchQueue.main.async {
                //code
                self.startCountdown()
            }
        }


    }
    //TODO: 查看详情
    @objc func seeDetails(btn:UIButton)
    {
        btn.superview?.isHidden = true
        btn.superview?.removeFromSuperview()
        if btn.titleLabel?.text != "知道了" {
            self.ID = btn .tag
            
            if self.delegate != nil && (self.delegate?.responds(to: #selector(TalkfunExaminationViewDelegate.operateModel(_:))))!{
                self.delegate?.operateModel(btn.tag)
            }
        }
       
        
    }
    
    @objc func operateClick(btn:UIButton){
       
        
        let model = self.dataList[btn.tag] as! TalkfunQuestionnaire
        
        self.ID = model .id
        
        //print("触发查看或者作答")
        if (model.answerStatus == TalkfunAnswerStatusUnsubmitted && model.isEndOfTestPaper == false)
        {
            model.answerStatus = TalkfunAnswerStatusParticipated
        }
       
        if self.delegate != nil && (self.delegate?.responds(to: #selector(TalkfunExaminationViewDelegate.operateModel(_:))))!{
            self.delegate?.operateModel(model.id)
        }
        
    }

    
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        fatalError("init(coder:) has not been implemented")
    }
}


@objc protocol TalkfunExaminationViewDelegate : NSObjectProtocol {
    
    func operateModel(_ ID : NSInteger)
}
